var old_meetup_details;
var new_meetup_details;

// prepare the form when the DOM is ready 
$(document).ready(function() { 
    var topic = $("#m_update_topic"),
	address = $("#m_update_address"),
	date_from = $("#date_from"),
	date_to = $("#date_to"),
	time_from = $("#time_from"),
	time_to = $("#time_to"),
	description = $("#m_update_description"),
	options = {        //target:        '#output1',   // target element(s) to be updated with server response 
				beforeSubmit:  showRequest,  // pre-submit callback 
				success:       showResponse,  // post-submit callback 
				iframe: true,
 
				// other available options: 
				//url: '/group/'+ groupId + '/update/', 
				type:  'post',  
				dataType:  'json', 
 
				// $.ajax options can be used here too, for example: 
				timeout:   3000,
			},
			
	allFields = $([]).add(topic).add(address).add(date_from).add(date_to).add(time_from).add(time_to).add(description),

	tips = $("#validateTips"),
	
	submitted = false;
	
	old_meetup_details={
		topic:$('#m_update_topic').val(),
		address:$('#m_update_address').val(),
		date_from:$('#date_from').val(),
		time_from:$('#time_from').val(),
		date_to:$('#date_to').val(),
		time_to:$('#time_to').val(),
		description:$('#m_update_description').val(),
	};
	
	$("#dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 430,
			width: 400,
			resizable: false,
			modal: true,
			show: 'drop',
			hide: 'drop',
			buttons: {
				'重置修改':function(){
					reset();
				},
				'保存修改': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');

					bValid = bValid && checkLength(topic,"聚会主题",2,100);
					bValid = bValid && checkLength(address,"活动地点",6,300);
					bValid = bValid && checkLength(date_from,"活动起始日期",10,10);
					bValid = bValid && checkLength(date_from,"活动结束日期",10,10);
					bValid = bValid && checkLength(description,"动员的话",0,5000);

					//currently no reg test will be execute
					
					//bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					//bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
					//bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
					
					if (bValid) {
					//if validated, save the form to the server.
						$('#m_update_form').submit();
						submitted = true;
						$(this).dialog('close');
					}
				}
			},
			close: function() {
				//remove the checkbox for the reminder.
				//and the message in the tips
				//and the errors leave in fields
				if(submitted == false) reset();
				$('#notify_all').removeAttr("checked");
				
			}
		});
		
		    $('#m_update_form').submit(function() { 
				// inside event callbacks 'this' is the DOM element so we first 
				// wrap it in a jQuery object and then invoke ajaxSubmit 
				$(this).ajaxSubmit(options); 
		 
				// !!! Important !!! 
				// always return false to prevent standard browser submit and page navigation 
				return false; 
			}); 
		
		
		    // bind form using 'ajaxForm'
			//$('#m_update_form').ajaxForm(options);
		
		$('#edit_meetup').click(function() {
			$('#dialog').dialog('open');
		})
		.hover(
			function(){ 
				$(this).addClass("ui-state-hover"); 
			},
			function(){ 
				$(this).removeClass("ui-state-hover"); 
			}
		).mousedown(function(){
			$(this).addClass("ui-state-active"); 
		})
		.mouseup(function(){
				$(this).removeClass("ui-state-active");
		});
	
}); 

		function updateTips(t) {
			tips.text(t).effect("highlight",{},1500);
		}
		
		function reset(){
			updateTips("在下方输入要修改的信息");
			allFields.removeClass('ui-state-error');
			$('#m_update_topic').val(old_meetup_details.topic);
			$('#m_update_address').val(old_meetup_details.address);
			$('#date_from').val(old_meetup_details.date_from);
			$('#time_from').val(old_meetup_details.time_from);
			$('#date_to').val(old_meetup_details.date_to);
			$('#time_to').val(old_meetup_details.time_to);
			$('#m_update_description').val(old_meetup_details.description);
		}

		function checkLength(o,n,min,max) {

			if ( o.val().length > max || o.val().length < min ) {
				o.addClass('ui-state-error');
				updateTips("出错啦，" + n +"的长度"+ " 必须不小于"+min+" 并且不大于 "+max+"。");
				return false;
			} else {
				return true;
			}

		}

		function checkRegexp(o,regexp,n) {

			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass('ui-state-error');
				updateTips(n);
				return false;
			} else {
				return true;
			}

		}
		
				// pre-submit callback 
		function showRequest(formData, jqForm, options) { 
			// formData is an array; here we use $.param to convert it to a string to display it 
			// but the form plugin does this for you automatically when it submits the data 
		//    var queryString = $.param(formData); 
			new_meetup_details={
				topic:$('#m_update_topic').val(),
				address:$('#m_update_address').val(),
				date_from:$('#date_from').val(),
				time_from:$('#time_from').val(),
				date_to:$('#date_to').val(),
				time_to:$('#time_to').val(),
				description:$('#m_update_description').val(),
			};
			if(new_meetup_details.topic == old_meetup_details.topic
				&& new_meetup_details.address == old_meetup_details.address
				&& new_meetup_details.date_from == old_meetup_details.date_from
				&& new_meetup_details.time_from == old_meetup_details.time_from
				&& new_meetup_details.date_to == old_meetup_details.date_to
				&& new_meetup_details.time_to == old_meetup_details.time_to
				&& new_meetup_details.description == old_meetup_details.description)
			{
				return false;
			}
			return true; 
		} 
 
		// post-submit callback 
		function showResponse(responseText, statusText){ 
			old_meetup_details = new_meetup_details;
			new_meetup_details='';
			$(".disable_masking").hide();
			$("#floatdialog_mask_" + "dialogid").fadeOut('slow').fadeTo("", 100);

			$('label#status_label img').remove();
			$('label#status_label b').remove();
			
			
			$('.m_topic_field').each(function(){
				this.textContent = responseText.topic;
			});


			//location info
			$('.m_location').each(function(){
				this.textContent=responseText.address;
			});
			$('.m_description_field').each(function(){
				this.textContent = responseText.description;
			});
			
			//month/day/year
			var date_from_frags = responseText.date_from.split('/');
			$('.month').each(function(){
				this.textContent = date_from_frags[0] + "月";
			});
			$('.day').each(function(){
				this.textContent = date_from_frags[1];
			});
			
			var myDate=new Date();
			myDate.setFullYear(date_from_frags[2],date_from_frags[0]-1,date_from_frags[1]);
			var day = myDate.getDay();
			$('.dow').each(function(){
				this.textContent = chineseDoW[myDate.getDay()];
			});
			
			$('.time').each(function(){
				this.textContent = responseText.time_from;
			});
			
			var date_to_frags = responseText.date_to.split('/');
			$('.to_datetime').each(function(){
				this.textContent = responseText.time_to + "," + date_to_frags[2].substr(2,2) + "年"
									+ date_to_frags[0] +"月"+date_to_frags[1] + "日";
			});
		}
 